package org.example.hrpc.serializer.hessian;

import com.caucho.hessian.io.Hessian2Input;
import com.caucho.hessian.io.Hessian2Output;
import org.example.hrpc.serializer.Serializer;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

public class HessianSerializer implements Serializer {
    @Override
    public byte[] serialize(Object object) throws Exception {
        Hessian2Output hessian2Output = null;
        try(ByteArrayOutputStream bos = new ByteArrayOutputStream();) {
            hessian2Output = new Hessian2Output(bos);
            hessian2Output.writeObject(object);
            hessian2Output.flush();
            return bos.toByteArray();
        } finally {
            hessian2Output.close();
        }
    }

    @Override
    public <T> T deserialize(byte[] data, Class<T> cls) throws Exception {
        Hessian2Input hessian2Input = null;
        try(ByteArrayInputStream bis = new ByteArrayInputStream(data);) {
            hessian2Input = new Hessian2Input(bis);
            return (T) hessian2Input.readObject();
        } finally {
            hessian2Input.close();
        }
    }
}
